package lk.icta.mobile;

import lk.icta.common.entity.Document;
import lk.icta.common.entity.DocumentCategory;
import lk.icta.common.util.KmlWriter;
import lk.icta.core.dao.LandDAO;
import lk.icta.core.dto.GeoParcelCodeDetail;
import lk.icta.core.entity.GeoParcelCode;
import lk.icta.core.entity.Land;
import lk.icta.core.entity.ModuleType;
import lk.icta.core.service.LandManagementService;
import lk.icta.user.common.AuthorizationException;
import lk.icta.user.common.Base64;
import lk.icta.user.entity.User;
import lk.icta.user.service.UserManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Kusal Samarakoon
 */

public class MobileElandServlet extends HttpServlet {

    private static final Logger logger = LoggerFactory.getLogger(MobileElandServlet.class);

    private LandManagementService landManagementService;
    UserManager userManager;

    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
        WebApplicationContext context = WebApplicationContextUtils.getRequiredWebApplicationContext(config.getServletContext());

        landManagementService = (LandManagementService) context.getBean("landManagementService");
        userManager = (UserManager) context.getBean("userManager");

    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        logger.debug("Mobile Start...");

        response.setContentType("text/plain");
        response.setHeader("Cache-Control", "no-cache");
        PrintWriter out = response.getWriter();

        String action = request.getParameter("maction");
        logger.debug("action {}", action);

        if (action.equals("kmlSave")) {

            String uName = request.getParameter("userName");
            String pass = request.getParameter("password");
            String landId = request.getParameter("landId");
            String kmlData = request.getParameter("kmlData");
            String coordinate = request.getParameter("coordinate");
            //logger.debug("action {}", action + landId + uName + pass);
            boolean res = saveKmlMobile(Long.parseLong(landId), uName, pass, kmlData, coordinate);
            if (res) {
                out.println("success");
            } else {
                out.println("fail");
            }


        } else if (action.equals("fileUpload")) {
            try {
                // out.println("fileUpload");

                String uName = request.getParameter("userName");
                String pass = request.getParameter("password");
                String landId = request.getParameter("landId");
                String imagePath = request.getParameter("imagePath");
                String image = request.getParameter("image");
                //image.getBytes();
                logger.debug("image {}", image);

                byte[] imageByteArray = Base64.decode(image);

                imagePath = "temp.png";
                File imageFile = new File(imagePath);

                // Write a image byte array into file system
                FileOutputStream imageOutFile = new FileOutputStream(imagePath);
                imageOutFile.write(imageByteArray);

                imageOutFile.close();

                boolean res = saveMobileImage(Long.parseLong(landId), uName, pass, imagePath, imageFile);
                if (res) {
                    out.println("success");
                } else {
                    out.println("fail");
                }

            } catch (Exception ioe) {
                logger.debug("Exception while reading the Image " + ioe);
            }
        }
    }

    public boolean saveKmlMobile(long id, String userName, String password, String kmlData, String coordinate) {
        logger.debug("saveKmlMobile");
        User user;
        boolean res = false;
        try {
            user = userManager.authenticateUser(userName, userManager.hashPassword(password));
            Land mobileLand = landManagementService.getLandById(id);
            if (mobileLand != null) {
                //save the reference number
                KmlWriter kmlWriter = new KmlWriter();
                //logger.debug("Ref No {}", kmlWriter.getMiddlePoint(coordinate));
                //String middlePoint = kmlWriter.getMiddlePoint(coordinate);
                GeoParcelCodeDetail parcelCodeDetail = kmlWriter.getMiddlePoint(coordinate);

                String middlePoint = parcelCodeDetail.getLatitude() + "," + parcelCodeDetail.getLongitude() + "," +
                        parcelCodeDetail.getAltitude();


                //logger.debug("Kml Data {}", kmlData);
                mobileLand.setKmlString(coordinate);
                mobileLand.setKmlMiddlePoint(middlePoint);
                mobileLand.setKmlLandArea(null);

                GeoParcelCode geoParcelCode;
                geoParcelCode = new GeoParcelCode();

                if (parcelCodeDetail != null) {
                    
                    geoParcelCode.setLatitude(parcelCodeDetail.getLatitude());
                    geoParcelCode.setLongitude(parcelCodeDetail.getLongitude());
                    geoParcelCode.setAltitude(parcelCodeDetail.getAltitude());
                    logger.debug("GIS Parcel Code mobileLand {} ", geoParcelCode.toString());


                }


                landManagementService.updateLand(mobileLand, user);
                logger.debug(" successfully saving Test Mobile kml data");
                res = true;
            }

        } catch (AuthorizationException e) {
            //addActionError(getText("invalid_username_password.label"));
            user = null;
            logger.debug(" Error in saving Test Mobile kml data");
            res = false;
        }
        return res;

    }


    public boolean saveMobileImage(long id, String userName, String password, String imagePath, File file) {
        logger.debug("saveMobileImage");
        User user;
        boolean res = false;
        try {
            user = userManager.authenticateUser(userName, userManager.hashPassword(password));
            Land mobileLand = landManagementService.getLandById(id);
            if (mobileLand != null) {


                List<Document> docList = new ArrayList<Document>();
                if (imagePath != null && imagePath.length() > 0) {


                    Document document = new Document();

                    DocumentCategory docCategory = new DocumentCategory();
                    docCategory.setId(3);

                    document.setDocumentCategory(docCategory);

                    document.setContentType("image/png");
                    document.setModuleType(ModuleType.DETAILED_LAND);
                    document.setFile(file);
                    document.setFileName(file.getName());

                    //  if (nameOfDocument[i] == null || ("".equals(nameOfDocument[i]))) {
                    int dotPos = file.getName().indexOf('.');
                    if (dotPos != -1) {
                        document.setDocumentName(file.getName().substring(0, dotPos));
                    } else {
                        document.setDocumentName(file.getName());
                    }
                    /*} else {
                        document.setDocumentName(nameOfDocument[i]);
                    }    */
                    docList.add(document);


                }


                mobileLand.setDocumentList(docList);

                landManagementService.updateLand(mobileLand, user);
                logger.debug(" successfully saving  Mobile Image");
                res = true;
            }

        } catch (AuthorizationException e) {
            //addActionError(getText("invalid_username_password.label"));
            user = null;
            logger.debug(" Error in saving  Mobile Image");
            res = false;
        }
        return res;

    }


}
